<template>
    <div class="upload_image" v-loading="loading">
        <!--<span class="upload-delete" v-if="imageUrl" @click="deleteImage">删除</span>-->
        <el-upload :headers="headersParam" name="upFile" class="upload" :disabled="addCredit" :accept="acceptType"
                   :action="action" :show-file-list="false" :on-success="handleAvatarSuccess"
                   :before-upload="beforeAvatarUpload" :data="extData" :on-error="closeLoading">
            <el-button slot="trigger" class="no_border" type="text" icon="el-icon-upload" :disabled="addCredit">
                {{ $t('common.uploadImage') }}
            </el-button>
            <div v-if="!imageUrl && tips" class="img_desc">{{ tips }}</div>
        </el-upload>
    </div>
</template>

<script>
import Compressor from 'compressorjs';
import {apiConf} from '@/config';

export default {
    name: 'uploadImage',
    props: {
        value: {
            type: Object
        },
        name: {
            type: String,
            default: 'file'
        },
        action: {
            type: String,
            // default: `${apiConf.baseUrl}/admin/manage/upload`
            // default: 'http://47.98.120.246:8087/file-server/file/fileUpload'
            default: `${apiConf.baseUrl}/customer/file/fileUpload`
        },
        tips: {
            type: String,
            default: ''
        },
        addCredit: {
            type: Boolean,
            default: false,
        },
        isCompress: {
            type: Boolean,
            default: false,
        }
    },
    data() {
        return {
            user: this.$storage.get('user'),
            imageUrl: (this.value && this.value.url) || '',
            imageId: '',
            extData: {
                userId: 123456
            },
            headersParam: {
                token: this.$storage.get('user').token,
                language: 'zh',
                Authorization: 'Basic cGluamFtYW5nbzpwaW5qYW1hbmdvMDE4'
            },
            loading: false,
            acceptType: 'image/png,image/gif,image/jpg,image/jpeg,image/bmp,image/webp'
        };
    },
    watch: {
        'value.id'(val) {
            this.imageId = val;
        },
        'value.url'(val) {
            this.imageUrl = val;
        },
        imageUrl(val) {
            const {imageId} = this;
            this.$emit('input', {
                url: val,
                id: imageId
            });
        }
    },
    methods: {
        closeLoading() {
            this.loading = false;
        },
        deleteImage() {
            this.imageUrl = '';
        },
        handleAvatarSuccess(res, file) {
            this.closeLoading();
            const {status, data, msg} = res;
            if (status === '1') {
                // const {fileDomain, fileName, id} = data;
                const {url, id} = data;
                // this.imageUrl = fileDomain + fileName;
                this.imageUrl = url;
                this.imageId = id;
                // this.imageUrl = URL.createObjectURL(file.raw);
            } else {
                this.$message.error(msg || 'Image upload error, please try again later!'); // 图片上传出错，请稍后重试
            }
        },
        beforeAvatarUpload(file) {
            if (this.isCompress) {
                return new Promise((resolve, reject) => {
                    new Compressor(file, {
                        quality: 0.6,
                        convertSize: 100 * 1024,
                        success(newFile) {
                            resolve(newFile);
                        },
                        error(error) {
                            // eslint-disable-next-line no-console
                            console.log(error);
                            reject(error);
                        }
                    });
                });
            } else {
                const isPic = file.type.indexOf('image') === 0;
                const isLt2M = file.size / 1024 / 1024 <= 4;
                let flag = false;

                if (!isPic) {
                    this.$message.error('Can only upload image files!'); // 只能上传图片文件
                }

                if (!isLt2M) {
                    this.$message.error('Upload image size cannot exceed 4MB!'); // 上传图片大小不能超过 4MB!
                }

                flag = isPic && isLt2M;

                if (flag) {
                    this.loading = true;
                }

                return flag;
            }
        },
    }
};
</script>

<style lang="scss" scoped>
.upload_image {
    text-align: right;
}

.no_border {
    border: none;
    background-color: transparent;
}
</style>
